﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Acme.BookStore.Authors;
using Acme.BookStore.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace Acme.BookStore.EntityFrameworkCore
{
    public class AuthorRepository : EfCoreRepository<BookStoreDbContext, Author, Guid>, IAuthorRepository
    {
        public AuthorRepository(IDbContextProvider<BookStoreDbContext> dbContextProvider) : base(dbContextProvider)
        {

        }
        public async Task<Author> FindByNameAsync(string name)
        {
            return await this.FirstOrDefaultAsync(r => r.Name == name);
        }

        public async Task< (List<Author> authors, long? totalCount)> GetListAsync(int skipCount, int maxResultCount, string sorting, string filter = null, bool returnTotalCount = false)
        {
            long? totalCount = null;
            var data = this.WhereIf(!string.IsNullOrWhiteSpace(filter), r => r.Name.Contains(filter));
            if (returnTotalCount) totalCount = await data.CountAsync();
            var authors = await data
            .OrderBy(sorting)
            .Skip(skipCount)
            .Take(maxResultCount)
            .ToListAsync();
            return (authors, totalCount);
        }
    }
}
